<?php

namespace App\Http\Controllers\Alipay;
use App\Models\AuthenticLog;
use App\Models\Config;
use App\Models\MemberOther;
use App\Models\UserIdcardInfo;
use App\Models\Order;
use App\Services\AlipayMiniAppService;
use App\Services\AlipayRealpersonService;
use App\Services\AlipayService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\EsignV3Service;
use App\Services\XinyanService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\IdCardService;

class AuthenticController extends BaseController
{
    /**
     * 获取实名认证信息
     * @return false|string
     */
    public function getPersonAuth(){
        $data = [
            'mobile'=>!empty($this->member['mobile']) ? $this->member['mobile'] : '',
            'certName'=>!empty($this->member['cert_name']) ? $this->member['cert_name'] : '',
            'certNo'=>!empty($this->member['cert_no']) ? $this->member['cert_no'] : '',
            'cardFront'=>!empty($this->member['idcard_front']) ? $this->member['idcard_front'] : '',
            'cardBack'=>!empty($this->member['idcard_back']) ? $this->member['idcard_back'] : '',
        ];
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    /**
     * 实人认证
     * @param Request $request
     */
    public function realPersonAuth1(Request $request){
        $certName = $request->input('certName');
        $certNo = $request->input('certNo')?$request->input('certNo'):'';
        $orderId = $request->input('orderId')?$request->input('orderId'):'';
        $cardFront = $request->input('cardFront');
        $cardBack = $request->input('cardBack');
        $type = $request->input('type')?$request->input('type'):'1';

        $goods_id = $request->input('gooddsId')?$request->input('gooddsId'):'';

        if(!$certName || !$certNo ){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'姓名或身份证号码不能为空');
        }
         if (!check_passportid($certNo)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'身份证号无效');
         }

        $age=getAgeByID($certNo);
        if($age){
            $config = Config::settingDetail();
            if ($age < $config['min_age'] || $age > $config['max_age']) {
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '您年龄不符合要求', 'data' => []];//，需要大于18岁小于40岁
            }
        }

        $member = MemberOther::where(['id'=>$this->member['id']])
            ->select(
                "esign_user_id",'id','mobile','esign_seal_id'
            )
            ->first();
        if(empty($member['mobile'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未授权手机号码');
        }

        XinyanService::threeElementsFace(
            [
                'uid'=>$member['uid'],
                'cert_name'=>$certName,
                'cert_no'=>$certNo,
                'mobile'=>$member['mobile']
            ]
        );
        $cert_no=MemberOther::where(['id'=>$this->member['id']])->where('idcard_front','<>','')->value('cert_no');
        if(!$cert_no){

            if($cardFront&&$cardBack){
                $res=IdCardService::build(['infoImg'=>imgToBase64('https://img.qianbaozuji.com/'.$cardFront),'emblemImg'=>imgToBase64('https://img.qianbaozuji.com/'.$cardBack)]);
                if($res['curlRes']['code']!=0){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,$res['curlRes']['message']);
                }
                if($res['curlRes']['data']['name']!=$certName){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'填写的姓名与身份证不一致');
                }
                if($res['curlRes']['data']['idNo']!=$certNo){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'填写的身份证号与身份证不一致');
                }
                if($res['curlRes']['data']['validityPeriod']){
                    $validityPeriod=explode('-',$res['curlRes']['data']['validityPeriod']);
                    $dateString = $validityPeriod[1];
                    $dateArray = explode('.', $dateString); // 将日期分割为数组
                    $correctDateString = implode('-', $dateArray); // 将数组元素用 - 连接，得到正确的日期格式
                    $timestamp = strtotime($correctDateString); // 转换为时间戳
                    if($timestamp<time()){
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'身份证有效期已过期,请重新提交');
                    }
                }

            }

        }


        //创建个人账号
        if(empty($member['esign_user_id'])){
            $data1 = EsignV3Service::addPersonAccountID($certName,$certNo,$member['mobile']);
            if(!empty($data1['accountId'])){
                $esign_user_id = $data1['accountId'];
                MemberOther::where(['id'=>$this->member['id']])->update(['esign_user_id'=>$esign_user_id]);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
            }
        }else{
            $esign_user_id = EsignV3Service::updateAccounts($member['esign_user_id'],$certNo,$certName);
        }

        //创建个人印章
        if(empty($member['esign_seal_id'])){

            $seal_id = EsignV3Service::personaltemplate($esign_user_id);

            if($seal_id){
                MemberOther::where(['id'=>$this->member['id']])->update(['esign_seal_id'=>$seal_id]);
            }else{
                $flag = false;
            }
        }

        if(empty($esign_user_id)||empty($this->member)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'登录信息有误');
        }

        $response = EsignV3Service::checkFaceAuth($esign_user_id,$certName,$certNo,$type);//e签宝实人认证
        // dd($response);
        if($response){
            if($orderId){
                $authenticLog = AuthenticLog::where(['order_id'=>$orderId])->select('id')->first();
            }else{
                $authenticLog = AuthenticLog::where(['cert_no'=>$certNo,'order_id'=>0])->select('id')->orderBy('id','desc')->first();
            }

            $authenticLog = obToArray($authenticLog);
            //更改实名认证
            $resData = $response;
            $data = [
                'cert_no'=>$certNo,
                'cert_name'=>$certName,
                //更改实名认证
                'certify_id'=>$resData['flowId'],
                'idcard_front'=>$cardFront??'',
                'idcard_back'=>$cardBack??'',
                'request'=>json_encode($response),
            ];
            if($orderId){
                $data['order_id'] = $orderId;
                Order::where('id',$orderId)->update(['face_flow_id'=>$resData['flowId']]);
            }
            if($authenticLog){
                AuthenticLog::where(['id'=>$authenticLog['id']])->update($data);
            }else{
                AuthenticLog::insert($data);
            }

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'唤起实名认证成功',[
                //更改实名认证
                "faceToken" => $resData['faceToken'],
                "certify_id" => $resData['flowId'],
                "certify_url" => $resData['originalUrl']
            ]);
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'唤起实名认证失败');
    }
    /**
     * 实名认证跳转
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function checkPersonAuthUrl(Request $request){

        $certifyId = $request->input('certifyId');
//        $status = $request->input('status');
//        if(!$certifyId){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
//        }

        //更改实名认证
        if($certifyId){
            $data=EsignService::checkFaceStatusAuth($certifyId);
            if($data['status']=='SUCCESS'){
                //实名认证通过
                $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;

                $log = AuthenticLog::where(['certify_id'=>$certifyId])->select('id','cert_no','cert_name','idcard_front','idcard_back')->first();
                $log = obToArray($log);
                if($log){
                    AuthenticLog::where(['id'=>$log['id']])->update($update);
                }
            }
        }

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'查询成功',0707);
    }
    /**
     * 实名认证查询
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function checkPersonAuth(Request $request){
        $flow_id = $request->input('certifyId');

        $res=IdCardService::faceCheck($flow_id);
        if($flow_id&&$res['curlRes']['data']['status']=='SUCCESS'){
            //实名认证通过
            $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;

            $log = AuthenticLog::where(['certify_id'=>$flow_id])->select('id','cert_no','cert_name','idcard_front','idcard_back')->first();
            $log = obToArray($log);
            if($log){
                AuthenticLog::where(['id'=>$log['id']])->update($update);
            }

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'人脸认证成功',true);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'人脸认证失败',false);
        }
    }

    /**
     * 手机号授权解析
     * @param Request $request
     * @return false|string
     */
    public function grantAuthMobile(Request $request)
    {
        $mobileStr = $request->input('mobileStr');
        if (!$mobileStr) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }

        $miniId = AlipayMiniAppService::getInstance()->getMiniId();
        $res = AlipayService::alipayMobileAnalysis($miniId, ['mobileStr' => $mobileStr]);

        if ($res['status'] && isset($res['data']['mobile']) && $res['data']['mobile']) {
            $update = ['mobile' => $res['data']['mobile']];
            MemberOther::where(['id' => $this->member['id']])->update($update);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '手机号授权成功', $update);
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '手机号授权解析失败');
    }

    public function grantAuthIdNumber(Request $request)
    {
        $mobileStr = $request->input('mobileStr');
        if (!$mobileStr) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        $idNumber = json_decode($mobileStr, true);

        $miniId = AlipayMiniAppService::getInstance()->getMiniId();
        $res = AlipayService::alipayMobileAnalysis($miniId, ['mobileStr' => $idNumber['response']]);
        return $res;
//        if($res['status'] && isset($res['data']['mobile']) && $res['data']['mobile']){
//            $update = ['mobile'=>$res['data']['mobile']];
//            MemberOther::where(['id'=>$this->member['id']])->update($update);
//            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'手机号授权成功',$update);
//        }
//        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'手机号授权成功',['mobile'=>15999999999]);
//         return ReturnMsg(CommonService::HTTP_CODE_FAIL, '手机号授权解析失败');
    }

    /**
     * 下单智能合同中转页面，获取用户实名认证信息
     */
    public function getAuthentic(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $log = AuthenticLog::where(['order_id'=>$order_id])->select('cert_no','cert_name','status')->first();
            $log = obToArray($log);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$log);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }

    }

}
